<?php

class System_Loader
{

    /**
     * Sets the include_path configuration option
     *
     * @return void
     */
    public function setIncludePath($path)
    {
        set_include_path(get_include_path() . PATH_SEPARATOR . $path);
    }

    /**
     * Loads a class from a PHP file.  The filename must be formatted
     * as "$class.php".
     *
     * @return void
     * @throws Exception
     */
    public static function loadClass($className)
    {
        if (class_exists($className, false) || interface_exists($className, false)) {
            return;
        }

        self::loadFile($className);

        if (!class_exists($className, false) && !interface_exists($className, false)) {
            throw new Exception("File \"$file\" does not exist or class \"$className\" was not found in the file");
        }
    }

    /**
     * Returns TRUE if the $filename is readable, or FALSE otherwise.
     * This function uses the PHP include_path, where PHP's is_readable()
     * does not.
     *
     * Note from ZF-2900:
     * If you use custom error handler, please check whether return value
     *  from error_reporting() is zero or not.
     * At mark of fopen() can not suppress warning if the handler is used.
     *
     * @param string   $filename
     * @return boolean
     */
    public static function isReadable($filename)
    {
        if (!$fh = @fopen($filename, 'r', TRUE)) {
            return FALSE;
        }
        return TRUE;
    }

    /**
     * Loads a PHP file.  This is a wrapper for PHP's include() function.
     *
     */
    public static function loadFile($name)
    {
        $file = str_replace('_', '/', $name) . '.php';

        return require_once $file;
    }

    /**
     * spl_autoload() suitable implementation for supporting class autoloading.
     *
     * @param  string $class
     * @return string|false Class name on success; false on failure
     */
    public static function autoload($className)
    {
        if (class_exists($className, FALSE)) return;

        if (strpos($className, '_') === false) {
            $filePath = $className;
        } else {
            $filePath = str_replace("_", "/", $className);
        }
        $fileName = $filePath.'.php';
        if (self::isReadable($fileName)) {
            require_once $fileName;
        }
    }

    /**
     * Register {@link autoload()} with spl_autoload()
     *
     * @param string $class (optional)
     * @param boolean $enabled (optional)
     * @return void
     * @throws Exception if spl_autoload() is not found
     * or if the specified class does not have an autoload() method.
     */
    public static function registerAutoload()
    {
        if (!function_exists('spl_autoload_register')) {
            throw new Exception('spl_autoload does not exist in this PHP installation');
        }

        spl_autoload_register(array('System_Loader', 'autoload'));
    }
}
